package summer.student.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import summer.student.Dao.*;
import summer.student.Domain.*;
import summer.student.Utils.Judge;
import summer.student.Utils.Result;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: student
 * @description:
 * @author: hlt
 * @create: 2023-07-10 09:25
 **/
@RestController
@RequestMapping("/courses")
@CrossOrigin(origins = "*", maxAge = 3600)  // 后端解决跨域
@Api(tags = "课程管理相关接口")
public class CourseController {
    @Autowired
    private CourseDao courseDao;

    @Autowired
    private ClassDao classDao;

    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private CollegeDictionaryDao collegeDictionaryDao;

    @Autowired
    private SelectCourseDao selectCourseDao;

    @GetMapping("/selectCourseList")
    public Result selectCourseList(@RequestParam(name="semester", required = false) String semester,
                                   @RequestParam(name="courseTitle", required = false) String courseTitle,
                                   @RequestParam(name = "currentPage", required = false, defaultValue = "1") int currentPage,
                                   @RequestParam(name="pageSize", required = false, defaultValue = "10") int pageSize){
//        System.out.println("data: " + data);
//        System.out.println("semester: " + semester);
        Page<Course> coursePage = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Course> clqw = new LambdaQueryWrapper<>();
        if(semester != "" && semester != null) clqw.eq(Course::getSemester, semester);
        if (courseTitle != "" && courseTitle != null) clqw.like(Course::getCourseTitle, courseTitle);  // 模糊查询："%courseTitle%"
//        List<Course> courses = courseDao.selectList(clqw);
        Page<Course> page = courseDao.selectPage(coursePage, clqw);
        return Result.Success(page);
    }

    @GetMapping("/selectCourseListWithoutScore")
    public Result selectCourseListWithoutScore(@RequestParam(name="semester", required = false) String semester,
                                               @RequestParam(name="courseTitle", required = false) String courseTitle,
                                               @RequestParam(name = "currentPage", required = false, defaultValue = "1") int currentPage,
                                               @RequestParam(name="pageSize", required = false, defaultValue = "10") int pageSize){
        Page<Course> coursePage = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Course> clqw = new LambdaQueryWrapper<>();
        if(semester != "" && semester != null) clqw.eq(Course::getSemester, semester);
        if (courseTitle != "" && courseTitle != null) clqw.like(Course::getCourseTitle, courseTitle);
        List<Course> courses = courseDao.selectList(clqw);
        ArrayList<Course> goodCourses = new ArrayList<>();
        for(Course course : courses){
            // 课程中如果有班级已经出分则不能再创建班级了
            boolean isShow = true;
            Long courseId = course.getCourseId();
            LambdaQueryWrapper<Classes> classesLQW = new LambdaQueryWrapper<>();
            classesLQW.eq(Classes::getCourseId, courseId);
            List<Classes> classes = classDao.selectList(classesLQW);
            for (Classes item : classes){
                Long classId = item.getClassId();
                LambdaQueryWrapper<SelectCourse> selectCourseLQW = new LambdaQueryWrapper<>();
                selectCourseLQW.eq(SelectCourse::getClassId, classId);
                List<SelectCourse> selectCourses = selectCourseDao.selectList(selectCourseLQW);
                for (SelectCourse selectCourse : selectCourses){
                    if (selectCourse.getScore() != null){
                        isShow = false;
                        break;
                    }
                }
                if (!isShow) break;
            }
            if (isShow) goodCourses.add(course);
        }
        int count = goodCourses.size();
        coursePage.setRecords(goodCourses);
        coursePage.setPages(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        coursePage.setTotal(count);
        return Result.Success(coursePage);
    }

    @GetMapping("/selectClassList")   // 返回可选课的班级(已经登录成绩的班级不能选课)
    public Result selectClassList(@RequestParam(name = "currentPage", defaultValue = "1", required = false) int currentPage,
                                  @RequestParam(name = "pageSize", defaultValue = "10", required = false)int pageSize){
        LambdaQueryWrapper<Course> courseLQW = new LambdaQueryWrapper<>();
        List<Course> courses = courseDao.selectList(courseLQW);
        ArrayList<ClassView> classViews = new ArrayList<>();
        Page<ClassView> classViewPage = new Page<>(currentPage, pageSize);
        // 先查询所有课程，再根据课程查询对应的班级信息
        // 整理传递给前端的信息
        // 这里的写法略显繁琐，请参见讲课内容使用stream流操作
        LambdaQueryWrapper<Classes> classLQW;  // 优化
        for (Course course : courses){
            Long courseId = course.getCourseId();
            classLQW = new LambdaQueryWrapper<>();
            classLQW.eq(Classes::getCourseId, courseId);
            List<Classes> classes = classDao.selectList(classLQW);
            for(Classes item : classes){
                ClassView classView = new ClassView();
                Long classId = item.getClassId();
                String teacherId = item.getTeacherId();
                Teacher teacher = teacherDao.selectById(item.getTeacherId());
                if (teacher == null && (teacherId != null && teacherId != "")) {
                    System.out.println("服务器内部错误！未查询到教师信息！");
                    System.out.println("teacherId: " + teacherId);
                    return Result.Error500("服务器内部错误！未查询到教师信息！");
                }
                classView.setClassId(classId);
                classView.setCourseId(courseId);
                classView.setCourseTitle(course.getCourseTitle());
                if (!(teacherId != null && teacherId != ""))   classView.setTeacherName(teacher.getTeacherName());
                classView.setSemester(course.getSemester());
                classView.setGpa(course.getGpa());
                classView.setCredit(course.getCredit());
                classView.setClassroom(item.getClassroom());

                classViews.add(classView);
            }
        }
        int count = classViews.size();
        classViewPage.setRecords(classViews);
        classViewPage.setTotal(count);
        classViewPage.setPages(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        classViewPage.setCurrent(currentPage);
        classViewPage.setSize(pageSize);
        return Result.Success(classViewPage);
    }

    @PostMapping("/addCourse")
    public Result addCourse(@RequestBody Map<String, String>data){
        String courseTitle = data.get("courseTitle");
        String teacherId = data.get("teacherId");
        double credit = Double.parseDouble(data.get("credit"));
        double gpa = Double.parseDouble(data.get("gpa"));
        String semester = data.get("semester");
        long college = Long.parseLong(data.get("college"));
        CollegeDictionary collegeDictionary = collegeDictionaryDao.selectById(college);
        if(collegeDictionary == null) return Result.Error("开课学院信息未找到！");
        if (semester == "" || courseTitle == "" || credit == 0 || teacherId == "") return Result.Error("数据不完整！");
        Teacher teacher = teacherDao.selectById(teacherId);
        if (teacher == null) return Result.Error("未查询到教师信息");
        Course course = new Course(null,teacher.getTeacherName(), courseTitle, credit, gpa, semester,collegeDictionary.getCollegeName());
        courseDao.insert(course);
        return Result.Success("创建课程成功！");
    }

//    @PostMapping("/setCourseStatus")
//    public Result setCourseStatus(Map<String, String>data){
//        String courseId = data.get("courseId");
//        int status = Integer.parseInt(data.get("status"));
//        LambdaQueryWrapper<Course> clqw = new LambdaQueryWrapper<>();
//        clqw.eq(Course::getCourseId,courseId);
//        Course course = courseDao.selectById(courseId);
//        if (course == null) return Result.Error("课程信息未找到！");
//        course.setStatus(status);
//        courseDao.update(course, clqw);
//        return Result.Success("修改课程状态成功");
//    }

    @PostMapping("/addClass")
    public Result addClass(@RequestBody Map<String, String>data){
        String teacherId = data.get("teacherId");
        long courseId = Long.parseLong(data.get("courseId"));
        String classroom = data.get("classroom");
        // 检验课程和老师是否存在
        LambdaQueryWrapper<Teacher> tlqw = new LambdaQueryWrapper<>();
        tlqw.eq(Teacher::getTeacherId, teacherId);
        Teacher teacher = teacherDao.selectOne(tlqw);
        if(teacher == null) return Result.Error("教师信息未找到！");
        System.out.println("courseId: " + courseId);
        Course course = courseDao.selectById(courseId);  // 使用selectById必须在domain中注明id字段
        if(course == null) return Result.Error("课程信息未找到！");

        if(teacherId == "" || courseId == 0 || classroom == "") return Result.Error("数据不完整！");
        classDao.insert(new Classes(null,teacherId,courseId,classroom));
        return Result.Success("创建课程成功！");
    }

}
